package com.wjjzst.io.nio;

import com.wjjzst.common.utils.file.OSUtil;

import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class FileLockDemo {

    public static void main(String[] args) throws Exception {
        // FileInputStream in = new FileInputStream(OSUtil.getBaseDir() + "/DataCenter/ruyuan/hello.txt");
        RandomAccessFile file = new RandomAccessFile(OSUtil.getBaseDir() + "/DataCenter/ruyuan/hello.txt", "rw");
        FileChannel channel = file.getChannel();
        channel.force(true);
        // 第三个为shared true共享锁 false为独占锁 共享锁的情况下不能写数据
        // 别的线程必须也要先获取共享锁再读取数据
        FileLock lock = channel.lock(0, Integer.MAX_VALUE, false);
        Thread.sleep(60 * 60 * 1000);
        channel.close();
        lock.release();
        file.close();
    }

}
